package com.lijiajia.cloud.resource.sys.service.numberid;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 时间戳 实现数字id服务
 * 生成规则: 17时间格式(毫秒级)+2随机数
 * 时间格式: yyyyMMddhhmmssSSS
 *
 * @author lijiajia
 * @since 2019-05-24
 */
@Slf4j
@Component
public class DateNumberIdService implements NumberIdService {
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
    private final long RANDOM_SIZE = 2L;
    private final Random random = new Random();


    @Override
    public Number get(String name) {
        String dateStr = OffsetDateTime.now().format(formatter);
        String randomStr = random.longs(RANDOM_SIZE, 0, 10)
                .mapToObj(String::valueOf)
                .collect(Collectors.joining());
        return Long.valueOf(dateStr.concat(randomStr));
    }

    @Override
    public String get(String name, String prefix) {
        return get(name, prefix, null);
    }

    @Override
    public String get(String name, String prefix, String suffix) {
        prefix = prefix == null ? "" : prefix;
        suffix = suffix == null ? "" : suffix;

        return prefix + get(prefix) + suffix;
    }

    @Override
    public void setValue(String name, Number value) {
        log.debug("时间戳NumberId策略 不能设置value");
    }

    @Override
    public void setIncrement(String name, Number increment) {
        log.debug("时间戳策略数字ID 不能设置increment");
    }
}
